import { defineStore } from 'pinia'
import { store } from "@/stores";
import {fetchCityList} from "@/service/city";

const useCityStore = defineStore({
  id: "city",
  state: () => ({
    citys: [],
    cityMap: {},
    updateTime: 0
  }),
  actions: {
    async getCity() {
      const now = Date.now()
      if(this.citys.length > 0 && now > this.updateTime) {
        return
      }
      const res = await fetchCityList();
      this.updateTime = now + 7*24*3600*1000
      this.citys = res.data
      this.citys.forEach((city: any) => {
        this.cityMap[city.name] = city
      })
    },
    getCityByName(name: string): any {
      return this.cityMap[name]
    },

  },
  persist: true,
})

export function useCityStoreHook() {
  return useCityStore(store);
}
